<?php
/**
*
* @package phpBB3
* @version $Id: rss.php 16 2009-02-24 14:22:00Z simbalala $
* @copyright (c) 2005 phpBB Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/

define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup('rss');

$forum_folder = (strlen($config['script_path']) > 1) ? $config['script_path'] . '/' : '/' ;
$xml_root_path = $config['server_protocol'] . $config['server_name']. $forum_folder;

date_default_timezone_set('UTC');

// Define initial vars
$bbcode_bitfield		= request_var('bbcode_bitfield', '');
$cat					= request_var('cat', 'cat');
$debug_output			= request_var('debug_output', '');
$forum_id				= request_var('f', 0); // %%RM
$forumname				= request_var('forumname', '');
$ignored				= request_var('ignored', '');
$keyword_search			= request_var('keyword_search', true);
$last_req_date			= request_var('last_req_date', '');
$mode					= request_var('mode', '');
$post_id				= request_var('p', 0);
$rsearch				= request_var('rsearch', 'rsearch'); // %%RM
$rss_atom_suffix		= request_var('rss_atom_suffix', '');
$rss_author				= request_var('rss_author', '');
$rss_config_name		= request_var('rss_config_name', '');
$rss_count_start		= request_var('rss_count_start', '');
$rss_last_request		= request_var('rss_last_request', '');
$rss_prefix				= request_var('rss_suffix', '');
$rss_total_views		= request_var('rss_total_views', '');
$rsssearch				= request_var('rsssearch', ''); // %%RM
$search_id				= request_var('search_id', '');
$search_in_author		= request_var('search_in_author', false);
$start					= max(request_var('start', 0), 0);
$temp					= request_var('temp', '');
$test					= request_var('test', '');
$timing_on				= request_var('timing_on', false);
$timing_result			= request_var('timing_result', '');
$topic_id				= request_var('t', 0);
$topic_title			= request_var('topic_title', '');
$topic_views			= request_var('topic_views', '');
$uid					= request_var('uid', 'uid'); // %%RM - RSS uid
$username				= request_var('username', '');
$username_from_id		= request_var('username_from_id', '');
$ut_offset 				= request_var('ut_offset', $config['board_timezone'] + $config['board_dst']);
$view					= request_var('view', '');
$xml_search				= request_var('xml_search', '');

$add_keywords			= utf8_normalize_nfc(request_var('add_keywords', '', true));
$authmailallow			= request_var('authmailallow', 1);
$author					= request_var('author', '', true);
$author_id				= request_var('author_id', 0);
$keywords				= utf8_normalize_nfc(request_var('keywords', '', true));
$return_chars			= request_var('ch', ($topic_id) ? -1 : 300);
$search_child			= request_var('sc', true);
$search_fields			= request_var('sf', 'all');
$search_forum			= request_var('fid', array(0));
$search_terms			= request_var('terms', 'all');
$show_results			= ($topic_id) ? 'posts' : request_var('sr', 'posts');
$show_results			= ($show_results == 'posts') ? 'posts' : 'topics';
$sort_days				= request_var('st', 0);
$sort_dir				= request_var('sd', 'd');
$sort_key				= request_var('sk', 't');
$submit					= request_var('submit', false);

// Set up config values, make sure a new install is ready to go

(!isset($config['rss_founder_only']))? 			set_config('rss_founder_only', 0, false) : '' ;
(!isset($config['rss_include_topic_views']))? 	set_config('rss_include_topic_views', 1, false) : '' ;
(!isset($config['rss_managing_editor']))? 		set_config('rss_managing_editor', current(explode('@', $config['board_contact'])), false) : '' ;
(!isset($config['rss_managing_editor_email']))? set_config('rss_managing_editor_email', $config['board_contact'], false) : '' ;
(!isset($config['rss_max_posts']))? 			set_config('rss_max_posts', 20, false) : '' ;
(!isset($config['rss_max_posts_main']))? 		set_config('rss_max_posts_main', 40, false) : '' ;
(!isset($config['rss_max_posts_srch']))? 		set_config('rss_max_posts_srch', 40, false) : '' ;
(!isset($config['rss_post_views']))? 			set_config('rss_post_views', 0, false) : '' ;
(!isset($config['rss_show_reply_count']))? 		set_config('rss_show_reply_count', 1, false) : '' ;
(!isset($config['rss_stats_reset']))? 			set_config('rss_stats_reset', 0, true) : '' ;
(!isset($config['rss_timing']))? 				set_config('rss_timing', 0, false) : '' ;
(!isset($config['rss_total_stats']))? 			set_config('rss_total_stats', 0, false) : '' ;
(!isset($config['rss_ttl']))? 					set_config('rss_ttl', 60, false) : '' ;

if ( $rsssearch ) // in case someone is still subscribed using the older format
{
	$rsearch = $rsssearch;
}

// People like to futz around with the url
$rsearch = strtolower($rsearch);

if	( $rsearch != 'yes' && $rsearch != 'no' && $rsearch != 'rsearch')
{
	$ignored = sprintf($user->lang['ARGUMENT']) . ' “' . $rsearch . '”';
	$template->assign_var('S_NO_SEARCH', true);
	trigger_error($ignored . sprintf($user->lang['INVALID_REQUEST']));
	die();
}

if ($uid != 'uid')
{
	if ($uid == 0 || !is_numeric($uid) || strval($uid) == 0)
	{
		trigger_error('NOT_VALID_UID_REQ');
		die();
	}
}

if ($cat != 'cat')
{
	if ($cat == 0 || !is_numeric($cat) || strval($cat) == 0)
	{
		trigger_error('NOT_VALID_CAT_REQ');
		die();
	}
}


// Begin main section

if ($config['rss_total_stats'])
{
	$sql = 'SELECT rss_views, rss_last_request, rss_count_start, rss_feed_type
		FROM ' . RSS_TRACK . "
		WHERE rss_id = 2";
		$result = $db->sql_query($sql);
		$row = $db->sql_fetchrow($result);
		$rss_total_views = number_format($row['rss_views']);

		// The next line may be needed if the server does not support strftime() as expected.
		// Uncomment the following line and comment out the next one, or try %z instead of %Z in the line containing strftime()
		// $rss_last_request = $row['rss_feed_type'] . str_replace('UTC', 'UT', date("H:i:s T" . $ut_offset . ", d M ‘y", ($row['rss_last_request'] + ($ut_offset * 3600))));
		$rss_count_start = str_replace('UTC', 'UT', strftime("%d %b ‘%y", $row['rss_count_start']));
		$rss_last_request = $row['rss_feed_type'] . str_replace('UTC', 'UT', strftime("%T %Z" . $ut_offset . ", %d %b ‘%y", ($row['rss_last_request'] + ($ut_offset * 3600))));
		$db->sql_freeresult($result);

	$sql = 'UPDATE ' . RSS_TRACK . '
		SET rss_views = rss_views + 1, rss_last_request = ' . time() . "
		WHERE rss_id = 2";
		$db->sql_query($sql);
}

if ($config['rss_stats_reset'])
{
	$sql = 'UPDATE ' . RSS_TRACK . '
		SET rss_views = 0, rss_count_start = ' . (((floor(time() / 86400)) * 86400) + 1) . "
		WHERE rss_id = 2";
		$db->sql_query($sql);

	set_config('rss_stats_reset', 0);
}

if	( $rsearch === 'yes' ) // If no, then it's a regular feed handled in the lower section (after: // Start of RSS forum-feed code)
{
	// Is user able to search? Has search been disabled?
	if (!$auth->acl_get('u_search') || !$auth->acl_getf_global('f_search') || !$config['load_search'])
	{
		$template->assign_var('S_NO_SEARCH', true);
		trigger_error('NO_SEARCH');
	}
	// Are any search arguments supplied?
	if (!$keywords && !$author && !$author_id && !$search_id && !$submit)
	{
		$template->assign_var('S_NO_SEARCH', true);
		trigger_error($ignored . sprintf($user->lang['NO_ARGUMENTS']));
		die();
	}

	// Check search load limit
	if ($user->load && $config['limit_search_load'] && ($user->load > doubleval($config['limit_search_load'])))
	{
		$template->assign_var('S_NO_SEARCH', true);
		trigger_error('NO_SEARCH_TIME');
	}

	// Check flood limit ... if applicable
	$interval = ($user->data['user_id'] == ANONYMOUS) ? $config['search_anonymous_interval'] : $config['search_interval'];
	if ($interval && !$auth->acl_get('u_ignoreflood'))
	{
		if ($user->data['user_last_search'] > time() - $interval)
		{
			$template->assign_var('S_NO_SEARCH', true);
			trigger_error('NO_SEARCH_TIME');
		}
	}

	// Define some vars
	$limit_days		= array(0 => $user->lang['ALL_RESULTS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
	$sort_by_text	= array('a' => $user->lang['SORT_AUTHOR'], 't' => $user->lang['SORT_TIME'], 'f' => $user->lang['SORT_FORUM'], 'i' => $user->lang['SORT_TOPIC_TITLE'], 's' => $user->lang['SORT_POST_SUBJECT']);

	$s_limit_days = $s_sort_key = $s_sort_dir = $u_sort_param = '';
	gen_sort_selects($limit_days, $sort_by_text, $sort_days, $sort_key, $sort_dir, $s_limit_days, $s_sort_key, $s_sort_dir, $u_sort_param);

	if ($keywords || $author || $author_id || $search_id || $submit)
		{
			// clear arrays
			$id_ary = array();

			// egosearch is an author search
			if ($search_id == 'egosearch')
			{
				$author_id = $user->data['user_id'];

				if ($user->data['user_id'] == ANONYMOUS)
				{
					login_box('', $user->lang['LOGIN_EXPLAIN_EGOSEARCH']);
				}
			}

			// If we are looking for authors get their ids
			$author_id_ary = array();
			if ($author_id)
			{
				$author_id_ary[] = $author_id;

				// get username via user_id for future use %%RM
				$sql = 'SELECT username
					FROM ' . USERS_TABLE . "
					WHERE user_id = $author_id";
					$result = $db->sql_query_limit($sql, 1);
					$username_from_id = $db->sql_fetchfield('username');
					$db->sql_freeresult($result);
			}
			else if ($author)
			{
				if ((strpos($author, '*') !== false) && (utf8_strlen(str_replace(array('*', '%'), '', $author)) < $config['min_search_author_chars']))
				{
					trigger_error(sprintf($user->lang['TOO_FEW_AUTHOR_CHARS'], $config['min_search_author_chars']));
				}

				$sql_where = (strpos($author, '*') !== false) ? ' username_clean ' . $db->sql_like_expression(str_replace('*', $db->any_char, utf8_clean_string($author))) : " username_clean = '" . $db->sql_escape(utf8_clean_string($author)) . "'";

				$sql = 'SELECT user_id
					FROM ' . USERS_TABLE . "
					WHERE $sql_where
						AND user_type IN (" . USER_NORMAL . ', ' . USER_FOUNDER . ')';
				$result = $db->sql_query_limit($sql, 100);

				while ($row = $db->sql_fetchrow($result))
				{
					$author_id_ary[] = (int) $row['user_id'];
				}
				$db->sql_freeresult($result);

				if (!sizeof($author_id_ary))
				{
					trigger_error('NO_SEARCH_RESULTS');
				}
			}

			// if we search in an existing search result just add the additional keywords. But we need to use "all search terms"-mode
			// so we can keep the old keywords in their old mode, but add the new ones as required words
			if ($add_keywords)
			{
				if ($search_terms == 'all')
				{
					$keywords .= ' ' . $add_keywords;
				}
				else
				{
					$search_terms = 'all';
					$keywords = implode(' |', explode(' ', preg_replace('#\s+#u', ' ', $keywords))) . ' ' .$add_keywords;
				}
			}

			// Which forums should not be searched? Author searches are also carried out in unindexed forums
			if (empty($keywords) && sizeof($author_id_ary))
			{
				$ex_fid_ary = array_keys($auth->acl_getf('!f_read', true));
			}
			else
			{
				$ex_fid_ary = array_unique(array_merge(array_keys($auth->acl_getf('!f_read', true)), array_keys($auth->acl_getf('!f_search', true))));
			}

			$not_in_fid = (sizeof($ex_fid_ary)) ? 'WHERE ' . $db->sql_in_set('f.forum_id', $ex_fid_ary, true) . " OR (f.forum_password <> '' AND fa.user_id <> " . (int) $user->data['user_id'] . ')' : "";

			$sql = 'SELECT f.forum_id, f.forum_name, f.parent_id, f.forum_type, f.right_id, f.forum_password, fa.user_id
				FROM ' . FORUMS_TABLE . ' f
				LEFT JOIN ' . FORUMS_ACCESS_TABLE . " fa ON (fa.forum_id = f.forum_id
					AND fa.session_id = '" . $db->sql_escape($user->session_id) . "')
				$not_in_fid
				ORDER BY f.left_id";
			$result = $db->sql_query($sql);

			$right_id = 0;
			$reset_search_forum = true;
			while ($row = $db->sql_fetchrow($result))
			{
				if ($row['forum_password'] && $row['user_id'] != $user->data['user_id'])
				{
					$ex_fid_ary[] = (int) $row['forum_id'];
					continue;
				}

				if (sizeof($search_forum))
				{
					if ($search_child)
					{
						if (in_array($row['forum_id'], $search_forum) && $row['right_id'] > $right_id)
						{
							$right_id = (int) $row['right_id'];
						}
						else if ($row['right_id'] < $right_id)
						{
							continue;
						}
					}

					if (!in_array($row['forum_id'], $search_forum))
					{
						$ex_fid_ary[] = (int) $row['forum_id'];
						$reset_search_forum = false;
					}
				}
			}
			$db->sql_freeresult($result);

			// find out in which forums the user is allowed to view approved posts
			if ($auth->acl_get('m_approve'))
			{
				$m_approve_fid_ary = array(-1);
				$m_approve_fid_sql = '';
			}
			else if ($auth->acl_getf_global('m_approve'))
			{
				$m_approve_fid_ary = array_diff(array_keys($auth->acl_getf('!m_approve', true)), $ex_fid_ary);
				$m_approve_fid_sql = ' AND (p.post_approved = 1' . ((sizeof($m_approve_fid_ary)) ? ' OR ' . $db->sql_in_set('p.forum_id', $m_approve_fid_ary, true) : '') . ')';
			}
			else
			{
				$m_approve_fid_ary = array();
				$m_approve_fid_sql = ' AND p.post_approved = 1';
			}

			if ($reset_search_forum)
			{
				$search_forum = array();
			}

			// Select which method we'll use to obtain the post_id or topic_id information
			$search_type = basename($config['search_type']);

			if (!file_exists($phpbb_root_path . 'includes/search/' . $search_type . '.' . $phpEx))
			{
				trigger_error('NO_SUCH_SEARCH_MODULE');
			}

			require("{$phpbb_root_path}includes/search/$search_type.$phpEx");

			// We do some additional checks in the module to ensure it can actually be utilised
			$error = false;
			$search = new $search_type($error);

			if ($error)
			{
				trigger_error($error);
			}

			// let the search module split up the keywords
			if ($keywords)
			{
				$correct_query = $search->split_keywords($keywords, $search_terms);
				if (!$correct_query || (empty($search->search_query) && !sizeof($author_id_ary) && !$search_id))
				{
					$ignored = (sizeof($search->common_words)) ? sprintf($user->lang['IGNORED_TERMS_EXPLAIN'], implode(' ', $search->common_words)) . '<br />' : '';
					trigger_error($ignored . sprintf($user->lang['NO_KEYWORDS'], $search->word_length['min'], $search->word_length['max']));
				}
			}

			if (!$keywords && sizeof($author_id_ary))
			{
				// if it is an author search we want to show topics by default
				$show_results = ($topic_id) ? 'posts' : request_var('sr', ($search_id == 'egosearch') ? 'topics' : 'posts');
				$show_results = ($show_results == 'posts') ? 'posts' : 'topics';
			}

			// define some variables needed for retrieving post_id/topic_id information
			$sort_by_sql = array('a' => 'u.username_clean', 't' => (($show_results == 'posts') ? 'p.post_time' : 't.topic_last_post_time'), 'f' => 'f.forum_id', 'i' => 't.topic_title', 's' => (($show_results == 'posts') ? 'p.post_subject' : 't.topic_title'));

			// pre-made searches
			$sql = $field = $l_search_title = '';
			if ($search_id)
			{
				switch ($search_id)
				{
					// Oh holy Bob, bring us some activity...
					case 'active_topics':
						$l_search_title = $user->lang['SEARCH_ACTIVE_TOPICS'];
						$show_results = 'topics';
						$sort_key = 't';
						$sort_dir = 'd';
						$sort_days = request_var('st', 7);
						$sort_by_sql['t'] = 't.topic_last_post_time';

						gen_sort_selects($limit_days, $sort_by_text, $sort_days, $sort_key, $sort_dir, $s_limit_days, $s_sort_key, $s_sort_dir, $u_sort_param);
						$s_sort_key = $s_sort_dir = '';

						$last_post_time_sql = ($sort_days) ? ' AND t.topic_last_post_time > ' . (time() - ($sort_days * 24 * 3600)) : '';

						$sql = 'SELECT t.topic_last_post_time, t.topic_id
							FROM ' . TOPICS_TABLE . " t
							WHERE t.topic_moved_id = 0
								$last_post_time_sql
								" . str_replace(array('p.', 'post_'), array('t.', 'topic_'), $m_approve_fid_sql) . '
								' . ((sizeof($ex_fid_ary)) ? ' AND ' . $db->sql_in_set('t.forum_id', $ex_fid_ary, true) : '') . '
							ORDER BY t.topic_last_post_time DESC';
						$field = 'topic_id';
					break;

					case 'unanswered':
						$l_search_title = $user->lang['SEARCH_UNANSWERED'];
						$show_results = request_var('sr', 'topics');
						$show_results = ($show_results == 'posts') ? 'posts' : 'topics';
						$sort_by_sql['t'] = ($show_results == 'posts') ? 'p.post_time' : 't.topic_last_post_time';
						$sort_by_sql['s'] = ($show_results == 'posts') ? 'p.post_subject' : 't.topic_title';
						$sql_sort = 'ORDER BY ' . $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');

						$sort_join = ($sort_key == 'f') ? FORUMS_TABLE . ' f, ' : '';
						$sql_sort = ($sort_key == 'f') ? ' AND f.forum_id = p.forum_id ' . $sql_sort : $sql_sort;

						if ($sort_days)
						{
							$last_post_time = 'AND p.post_time > ' . (time() - ($sort_days * 24 * 3600));
						}
						else
						{
							$last_post_time = '';
						}


						if ($sort_key == 'a')
						{
							$sort_join = USERS_TABLE . ' u, ';
							$sql_sort = ' AND u.user_id = p.poster_id ' . $sql_sort;
						}
						if ($show_results == 'posts')
						{
							$sql = "SELECT p.post_id
								FROM $sort_join" . POSTS_TABLE . ' p, ' . TOPICS_TABLE . " t
								WHERE t.topic_replies = 0
									AND p.topic_id = t.topic_id
									$last_post_time
									$m_approve_fid_sql
									" . ((sizeof($ex_fid_ary)) ? ' AND ' . $db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '') . "
									$sql_sort";
							$field = 'post_id';
						}
						else
						{
							$sql = 'SELECT DISTINCT ' . $sort_by_sql[$sort_key] . ", p.topic_id
								FROM $sort_join" . POSTS_TABLE . ' p, ' . TOPICS_TABLE . " t
								WHERE t.topic_replies = 0
									AND t.topic_moved_id = 0
									AND p.topic_id = t.topic_id
									$last_post_time
									$m_approve_fid_sql
									" . ((sizeof($ex_fid_ary)) ? ' AND ' . $db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '') . "
								$sql_sort";
							$field = 'topic_id';
						}
					break;

					case 'newposts':
						$l_search_title = $user->lang['SEARCH_NEW'];
						// force sorting
						$show_results = (request_var('sr', 'topics') == 'posts') ? 'posts' : 'topics';
						$sort_key = 't';
						$sort_dir = 'd';
						$sort_by_sql['t'] = ($show_results == 'posts') ? 'p.post_time' : 't.topic_last_post_time';
						$sql_sort = 'ORDER BY ' . $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');

						gen_sort_selects($limit_days, $sort_by_text, $sort_days, $sort_key, $sort_dir, $s_limit_days, $s_sort_key, $s_sort_dir, $u_sort_param);
						$s_sort_key = $s_sort_dir = $u_sort_param = $s_limit_days = '';

						if ($show_results == 'posts')
						{
							$sql = 'SELECT p.post_id
								FROM ' . POSTS_TABLE . ' p
								WHERE p.post_time > ' . $user->data['user_lastvisit'] . "
									$m_approve_fid_sql
									" . ((sizeof($ex_fid_ary)) ? ' AND ' . $db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '') . "
								$sql_sort";
							$field = 'post_id';
						}
						else
						{
							$sql = 'SELECT t.topic_id
								FROM ' . TOPICS_TABLE . ' t
								WHERE t.topic_last_post_time > ' . $user->data['user_lastvisit'] . '
									AND t.topic_moved_id = 0
									' . str_replace(array('p.', 'post_'), array('t.', 'topic_'), $m_approve_fid_sql) . '
									' . ((sizeof($ex_fid_ary)) ? 'AND ' . $db->sql_in_set('t.forum_id', $ex_fid_ary, true) : '') . "
								$sql_sort";
							$field = 'topic_id';
						}
					break;

					case 'egosearch':
						$l_search_title = $user->lang['SEARCH_SELF'];
					break;
				}
			}

			// show_results should not change after this
			$per_page = ($show_results == 'posts') ? $config['posts_per_page'] : $config['topics_per_page']; //%%RM ignored
			$total_match_count = 0;

			if ($search_id)
			{
				if ($sql)
				{
					// only return up to 1000 ids (the last one will be removed later)
					$result = $db->sql_query_limit($sql, 1001 - $start, $start);

					while ($row = $db->sql_fetchrow($result))
					{
						$id_ary[] = $row[$field];
					}
					$db->sql_freeresult($result);

					$total_match_count = sizeof($id_ary) + $start;
					$id_ary = array_slice($id_ary, 0, $config['rss_max_posts_srch']);
				}
				else
				{
					$search_id = '';
				}
			}

			// make sure that some arrays are always in the same order
			sort($ex_fid_ary);
			sort($m_approve_fid_ary);
			sort($author_id_ary);

			if (!empty($search->search_query))
			{
				$total_match_count = $search->keyword_search($show_results, $search_fields, $search_terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $m_approve_fid_ary, $topic_id, $author_id_ary, $id_ary, $start,  $config['rss_max_posts_srch']);
			}
			else if (sizeof($author_id_ary))
			{
				$firstpost_only = ($search_fields === 'firstpost') ? true : false;
				$total_match_count = $search->author_search($show_results, $firstpost_only, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $m_approve_fid_ary, $topic_id, $author_id_ary, $id_ary, $start, $config['rss_max_posts_srch']);
			}

			// For some searches we need to print out the "no results" page directly to allow re-sorting/refining the search options.
			if (!sizeof($id_ary) && !$search_id)
			{
				trigger_error('NO_SEARCH_RESULTS');
			}

			$sql_where = '';

			if (sizeof($id_ary))
			{
				$sql_where .= $db->sql_in_set(($show_results == 'posts') ? 'p.post_id' : 't.topic_id', $id_ary);
				$sql_where .= (sizeof($ex_fid_ary)) ? ' AND (' . $db->sql_in_set('f.forum_id', $ex_fid_ary, true) . ' OR f.forum_id IS NULL)' : '';
				$sql_where .= ($show_results == 'posts') ? $m_approve_fid_sql : str_replace(array('p.post_approved', 'p.forum_id'), array('t.topic_approved', 't.forum_id'), $m_approve_fid_sql);
			}

			if ($show_results == 'posts')
			{
				include($phpbb_root_path . 'includes/functions_posting.' . $phpEx);
			}
			else
			{
				include($phpbb_root_path . 'includes/functions_display.' . $phpEx);
			}

			$user->add_lang('viewtopic');

			// Grab icons
			$icons = $cache->obtain_icons();

			// Output header
			if ($search_id && ($total_match_count > 1000))
			{
				// limit the number to 1000 for pre-made searches
				$total_match_count--;
				$l_search_matches = sprintf($user->lang['FOUND_MORE_SEARCH_MATCHES'], $total_match_count);
			}
			else
			{
				$l_search_matches = ($total_match_count == 1) ? sprintf($user->lang['FOUND_SEARCH_MATCH'], $total_match_count) : sprintf($user->lang['FOUND_SEARCH_MATCHES'], $total_match_count);
				$l_found_search_posts = ($total_match_count == 1) ? sprintf($user->lang['FOUND_SEARCH_POST']) : sprintf($user->lang['FOUND_SEARCH_POSTS']);
			}

			if  (($keywords && ($author || $author_id)) || $author || $author_id ) //%%RM Set up variables for headers in template
			{
				$search_in_author = true;
				$keyword_search = false;
			}

			// define some vars for urls
			$hilit = implode('|', explode(' ', preg_replace('#\s+#u', ' ', str_replace(array('+', '-', '|', '(', ')', '&quot;'), ' ', $keywords))));
			// Do not allow *only* wildcard being used for hilight
			$hilit = (strspn($hilit, '*') === strlen($hilit)) ? '' : $hilit;

			$u_hilit = urlencode(htmlspecialchars_decode(str_replace('|', ' ', $hilit)));
			$u_show_results = ($show_results != 'posts') ? '&amp;sr=' . $show_results : '';
			$u_search_forum = implode('&amp;fid%5B%5D=', $search_forum);

			$u_search  = ("{$xml_root_path}rss.$phpEx?rsearch=yes&amp;" . $u_sort_param . $u_show_results); // %%RM - removed sid for RSS subscribers, they don't need it and it confuses the hell out of the Atom self reference link
			$u_search .= ($search_id) ? '&amp;search_id=' . $search_id : '';
			$u_search .= ($u_hilit) ? '&amp;keywords=' . urlencode(htmlspecialchars_decode($search->search_query)) : '';
			$u_search .= ($topic_id) ? '&amp;t=' . $topic_id : '';
			$u_search .= ($author) ? '&amp;author=' . urlencode(htmlspecialchars_decode($author)) : '';
			$u_search .= ($author_id) ? '&amp;author_id=' . $author_id : '';
			$u_search .= ($u_search_forum) ? '&amp;fid%5B%5D=' . $u_search_forum : '';
			$u_search .= (!$search_child) ? '&amp;sc=0' : '';
			$u_search .= ($search_fields != 'all') ? '&amp;sf=' . $search_fields : '';
			$u_search .= ($return_chars != 300) ? '&amp;ch=' . $return_chars : '';

			($keywords) ? $l_keywords = sprintf($user->lang['QUOTE_OPEN']) . str_replace(' ', '+', $keywords) . sprintf($user->lang['QUOTE_CLOSE']) : $l_keywords = '';
			($author) ? $l_author =  $author : $l_author = '';
			($username_from_id) ? $l_author = $username_from_id : $l_author = '';

			if (($keywords && $author) || ($keywords && $username_from_id))
			{
				$l_and = ' ' . $user->lang['AND_LOWER_CASE'] . ' ';
			}
			else
			{
				$l_and = '';
			}

				$template->assign_vars(array(
				'RSS_SEARCH'			=> true,
				'RSS_POST'				=> $user->lang['RSS_POST'],
				'RSS_POST_INFO'			=> $user->lang['RSS_POST_INFO'],
				'XML_HEADER'			=> '?xml version="1.0" encoding="ISO-8859-15"?',
				'XML_SITE_LOGO'			=> str_replace($phpbb_root_path,$config['server_protocol'].$config['server_name'].$forum_folder,$user->img('site_logo','','','','src')),
				'XML_SITE'				=> $config['server_protocol'].$config['server_name'].$forum_folder,
				'ATOM_LINK'				=> $u_search, // %%RM - add Atom link
				'RSS_TTL'				=> $config['rss_ttl'],
				'RSS_LANGUAGE'			=> str_replace('_', '-', $config['default_lang']),
				'MANAGING_EDITOR'		=> htmlspecialchars($config['rss_managing_editor_email'] . ' (' . $config['rss_managing_editor'] . ')'),
				'KEYWORDS'				=> $keywords,
				'SEARCH_TITLE'			=> $l_search_title,
				'SEARCH_MATCHES'		=> $l_search_matches,
				'RSS_SITENAME'			=> $user->lang['SITENAME_PREFIX_SRCH'] . $l_author . $l_and . $l_keywords . ' :: ' . htmlspecialchars($config['sitename']),
				'RSS_DESCRIPTION'		=> $l_search_matches .  ' ' . $user->lang['FOR'] . ' ' . $l_author . $l_and . str_replace(' ', '+', $l_keywords),
				'FOUND_SEARCH_POSTS'	=> $l_found_search_posts,
				'KEYWORDS_PLUS'			=> str_replace(' ', '+', $keywords),
				'SEARCH_IN_AUTHOR'		=> $search_in_author,
				'KEYWORD_SEARCH'		=> $keyword_search,
				'SEARCH_WORDS'			=> $search->search_query,
				'TOTAL_MATCHES'			=> $total_match_count,
				'SEARCH_IN_RESULTS'		=> ($search_id) ? false : true,

				'S_SELECT_SORT_DIR'		=> $s_sort_dir,
				'S_SELECT_SORT_KEY'		=> $s_sort_key,
				'S_SELECT_SORT_DAYS'	=> $s_limit_days,
				'S_SEARCH_ACTION'		=> $u_search,
				'S_SHOW_TOPICS'			=> ($show_results == 'posts') ? false : true,

				'U_XML_SEARCH_WORDS' 	=> $xml_search, //RSS MODD
				'U_SEARCH_WORDS'		=> $u_search,
			));

			if ($sql_where)
			{
				if ($show_results == 'posts')
				{
					// @todo Joining this query to the one below?
					// RSS: We ignore friends or foes for the rss feeds. If the user doesn't want to view the authors's post then don't view it.
					// ** the block is left in place for future compares with new search.php releases **
					// 	$sql = 'SELECT zebra_id, friend, foe
					// 		FROM ' . ZEBRA_TABLE . '
					// 		WHERE user_id = ' . $user->data['user_id'];
					// 	$result = $db->sql_query($sql);
					//
					// 	$zebra = array();
					// 	while ($row = $db->sql_fetchrow($result))
					// 	{
					// 		$zebra[($row['friend']) ? 'friend' : 'foe'][] = $row['zebra_id'];
					// 	}
					// 	$db->sql_freeresult($result);

					$sql = 'SELECT p.*, f.forum_id, f.forum_name, t.*, u.username, u.username_clean, u.user_sig, u.user_sig_bbcode_uid, u.user_colour
						FROM ' . POSTS_TABLE . ' p
							LEFT JOIN ' . TOPICS_TABLE . ' t ON (p.topic_id = t.topic_id)
							LEFT JOIN ' . FORUMS_TABLE . ' f ON (p.forum_id = f.forum_id)
							LEFT JOIN ' . USERS_TABLE . " u ON (p.poster_id = u.user_id)
						WHERE $sql_where";
				}

				else
				{
					$sql_from = TOPICS_TABLE . ' t
						LEFT JOIN ' . FORUMS_TABLE . ' f ON (f.forum_id = t.forum_id)
						' . (($sort_key == 'a') ? ' LEFT JOIN ' . USERS_TABLE . ' u ON (u.user_id = t.topic_poster) ' : '');
					$sql_select = 't.*, f.forum_id, f.forum_name';

					if ($user->data['is_registered'])
					{
						if ($config['load_db_track'] && $author_id !== $user->data['user_id'])
						{
							$sql_from .= ' LEFT JOIN ' . TOPICS_POSTED_TABLE . ' tp ON (tp.user_id = ' . $user->data['user_id'] . '
								AND t.topic_id = tp.topic_id)';
							$sql_select .= ', tp.topic_posted';
						}

						if ($config['load_db_lastread'])
						{
							$sql_from .= ' LEFT JOIN ' . TOPICS_TRACK_TABLE . ' tt ON (tt.user_id = ' . $user->data['user_id'] . '
									AND t.topic_id = tt.topic_id)
								LEFT JOIN ' . FORUMS_TRACK_TABLE . ' ft ON (ft.user_id = ' . $user->data['user_id'] . '
									AND ft.forum_id = f.forum_id)';
							$sql_select .= ', tt.mark_time, ft.mark_time as f_mark_time';
						}
					}

					if ($config['load_anon_lastread'] || ($user->data['is_registered'] && !$config['load_db_lastread']))
					{
						$tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
						$tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
					}

					$sql = "SELECT $sql_select
						FROM $sql_from
						WHERE $sql_where";
				}
				$sql .= ' ORDER BY ' . $sort_by_sql[$sort_key] . ' ' . (($sort_dir == 'd') ? 'DESC' : 'ASC');
				$result = $db->sql_query($sql);
				$result_topic_id = 0;

				$rowset = array();

				if ($show_results == 'topics')
				{
					$forums = $rowset = $shadow_topic_list = array();
					while ($row = $db->sql_fetchrow($result))
					{
						if ($row['topic_status'] == ITEM_MOVED)
						{
							$shadow_topic_list[$row['topic_moved_id']] = $row['topic_id'];
						}

						$rowset[$row['topic_id']] = $row;

						if (!isset($forums[$row['forum_id']]) && $user->data['is_registered'] && $config['load_db_lastread'])
						{
							$forums[$row['forum_id']]['mark_time'] = $row['f_mark_time'];
						}
						$forums[$row['forum_id']]['topic_list'][] = $row['topic_id'];
						$forums[$row['forum_id']]['rowset'][$row['topic_id']] = &$rowset[$row['topic_id']];
					}
					$db->sql_freeresult($result);

					// If we have some shadow topics, update the rowset to reflect their topic information
					if (sizeof($shadow_topic_list))
					{
						$sql = 'SELECT *
							FROM ' . TOPICS_TABLE . '
							WHERE ' . $db->sql_in_set('topic_id', array_keys($shadow_topic_list));
						$result = $db->sql_query($sql);

						while ($row = $db->sql_fetchrow($result))
						{
							$orig_topic_id = $shadow_topic_list[$row['topic_id']];

							// We want to retain some values
							$row = array_merge($row, array(
								'topic_moved_id'	=> $rowset[$orig_topic_id]['topic_moved_id'],
								'topic_status'		=> $rowset[$orig_topic_id]['topic_status'],
								'forum_name'		=> $rowset[$orig_topic_id]['forum_name'])
							);

							$rowset[$orig_topic_id] = $row;
						}
						$db->sql_freeresult($result);
					}
					unset($shadow_topic_list);

					foreach ($forums as $forum_id => $forum)
					{
						if ($user->data['is_registered'] && $config['load_db_lastread'])
						{
							$topic_tracking_info[$forum_id] = get_topic_tracking($forum_id, $forum['topic_list'], $forum['rowset'], array($forum_id => $forum['mark_time']), ($forum_id) ? false : $forum['topic_list']);
						}
						else if ($config['load_anon_lastread'] || $user->data['is_registered'])
						{
							$topic_tracking_info[$forum_id] = get_complete_topic_tracking($forum_id, $forum['topic_list'], ($forum_id) ? false : $forum['topic_list']);

							if (!$user->data['is_registered'])
							{
								$user->data['user_lastmark'] = (isset($tracking_topics['l'])) ? (int) (base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate']) : 0;
							}
						}
					}
					unset($forums);
				}
				else // Search Posts starts
				{
					$bbcode_bitfield = $text_only_message = '';
					$attach_list = array();

					while ($row = $db->sql_fetchrow($result))
					{
						// We pre-process some variables here for later usage
						$row['post_text'] = censor_text($row['post_text']);

						$text_only_message = $row['post_text'];
						// make list items visible as such
						if ($row['bbcode_uid'])
						{
							$text_only_message = str_replace('[*:' . $row['bbcode_uid'] . ']', '&sdot;&nbsp;', $text_only_message);
							// no BBCode in text only message
							strip_bbcode($text_only_message, $row['bbcode_uid']);
						}

						if ($return_chars == -1 || utf8_strlen($text_only_message) < ($return_chars + 3))
						{
							$row['display_text_only'] = false;
							$bbcode_bitfield = $bbcode_bitfield | base64_decode($row['bbcode_bitfield']);

							// Does this post have an attachment? If so, add it to the list
							if ($row['post_attachment'] && $config['allow_attachments'])
							{
								$attach_list[$row['forum_id']][] = $row['post_id'];
							}
						}
						else
						{
							$row['post_text'] = $text_only_message;
							$row['display_text_only'] = true;
						}

						$rowset[] = $row;
					}
					$db->sql_freeresult($result);

					unset($text_only_message);

					// Instantiate BBCode if needed
					if ($bbcode_bitfield !== '')
					{
						include_once($phpbb_root_path . 'includes/bbcode.' . $phpEx);
						$bbcode = new bbcode(base64_encode($bbcode_bitfield));
					}

					// Pull attachment data
					if (sizeof($attach_list))
					{
						$use_attach_list = $attach_list;
						$attach_list = array();

						foreach ($use_attach_list as $forum_id => $_list)
						{
							if ($auth->acl_get('u_download') && $auth->acl_get('f_download', $forum_id))
							{
								$attach_list = array_merge($attach_list, $_list);
							}
						}
					}

					if (sizeof($attach_list))
					{
						$sql = 'SELECT *
							FROM ' . ATTACHMENTS_TABLE . '
							WHERE ' . $db->sql_in_set('post_msg_id', $attach_list) . '
								AND in_message = 0
							ORDER BY filetime DESC, post_msg_id ASC';
						$result = $db->sql_query($sql);

						while ($row = $db->sql_fetchrow($result))
						{
							$attachments[$row['post_msg_id']][] = $row;
						}
						$db->sql_freeresult($result);
					}
				}

				if ($hilit)
				{
					// Remove bad highlights
					$hilit_array = array_filter(explode('|', $hilit), 'strlen');
					foreach ($hilit_array as $key => $value)
					{
						$hilit_array[$key] = str_replace('\*', '\w*?', preg_quote($value, '#'));
						$hilit_array[$key] = preg_replace('#(^|\s)\\\\w\*\?(\s|$)#', '$1\w+?$2', $hilit_array[$key]);
					}
					$hilit = implode('|', $hilit_array);
				}

				foreach ($rowset as $row)
				{
					$forum_id = $row['forum_id'];
					$result_topic_id = $row['topic_id'];
					$topic_title = censor_text($row['topic_title']);

					// we need to select a forum id for this global topic
					if (!$forum_id)
					{
						if (!isset($g_forum_id))
						{
							// Get a list of forums the user cannot read
							$forum_ary = array_unique(array_keys($auth->acl_getf('!f_read', true)));

							// Determine first forum the user is able to read (must not be a category)
							$sql = 'SELECT forum_id
								FROM ' . FORUMS_TABLE . '
								WHERE forum_type = ' . FORUM_POST;

							if (sizeof($forum_ary))
							{
								$sql .= ' AND ' . $db->sql_in_set('forum_id', $forum_ary, true);
							}

							$result = $db->sql_query_limit($sql, 1);
							$g_forum_id = (int) $db->sql_fetchfield('forum_id');
						}
						$u_forum_id = $g_forum_id;
					}
					else
					{
						$u_forum_id = $forum_id;
					}

					$view_topic_url = ("{$xml_root_path}viewtopic.$phpEx" . '?' . "f=$u_forum_id&amp;t=$result_topic_id" . (($u_hilit) ? "&amp;hilit=$u_hilit" : '')); //%%RM - remove sid

					$replies = ($auth->acl_get('m_approve', $forum_id)) ? $row['topic_replies_real'] : $row['topic_replies'];

					if ($show_results == 'topics')
					{
						$folder_img = $folder_alt = $topic_type = '';
						topic_status($row, $replies, (isset($topic_tracking_info[$forum_id][$row['topic_id']]) && $row['topic_last_post_time'] > $topic_tracking_info[$forum_id][$row['topic_id']]) ? true : false, $folder_img, $folder_alt, $topic_type);

						$unread_topic = (isset($topic_tracking_info[$forum_id][$row['topic_id']]) && $row['topic_last_post_time'] > $topic_tracking_info[$forum_id][$row['topic_id']]) ? true : false;

						$topic_unapproved = (!$row['topic_approved'] && $auth->acl_get('m_approve', $forum_id)) ? true : false;
						$posts_unapproved = ($row['topic_approved'] && $row['topic_replies'] < $row['topic_replies_real'] && $auth->acl_get('m_approve', $forum_id)) ? true : false;
						$u_mcp_queue = ($topic_unapproved || $posts_unapproved) ? append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=queue&amp;mode=' . (($topic_unapproved) ? 'approve_details' : 'unapproved_posts') . "&amp;t=$result_topic_id", true, $user->session_id) : '';

						$row['topic_title'] = preg_replace('#(?!<.*)(?<!\w)(' . $hilit . ')(?!\w|[^<>]*(?:</s(?:cript|tyle))?>)#is', '<span class="posthilit">$1</span>', $row['topic_title']);

						$tpl_ary = array(
							'PUNDATE'			        => str_replace('UTC', 'UT', date("D, d M Y H:i:s T", $row['topic_last_post_time'])),
							'RSS_TOPIC_AUTHOR'			=> ($authmailallow['user_allow_viewemail'] == 1 && !$row['topic_last_poster_name'] == 'Anonymous') ? '<dc:creator>' . $row['topic_last_poster_name'] . '</dc:creator>' : '',
							'TOPIC_AUTHOR'				=> get_username_string('username', $row['topic_poster'], $row['topic_first_poster_name'], $row['topic_first_poster_colour']),
							'TOPIC_AUTHOR_COLOUR'		=> get_username_string('colour', $row['topic_poster'], $row['topic_first_poster_name'], $row['topic_first_poster_colour']),
							'TOPIC_AUTHOR_FULL'			=> get_username_string('full', $row['topic_poster'], $row['topic_first_poster_name'], $row['topic_first_poster_colour']),
							'FIRST_POST_TIME'			=> $user->format_date($row['topic_time']),
							'LAST_POST_SUBJECT'			=> $row['topic_last_post_subject'],
							'LAST_POST_TIME'			=> $user->format_date($row['topic_last_post_time']),
							'LAST_VIEW_TIME'			=> $user->format_date($row['topic_last_view_time']),
							'LAST_POST_AUTHOR'			=> get_username_string('username', $row['topic_last_poster_id'], $row['topic_last_poster_name'], $row['topic_last_poster_colour']),
							'LAST_POST_AUTHOR_COLOUR'	=> get_username_string('colour', $row['topic_last_poster_id'], $row['topic_last_poster_name'], $row['topic_last_poster_colour']),
							'LAST_POST_AUTHOR_FULL'		=> get_username_string('full', $row['topic_last_poster_id'], $row['topic_last_poster_name'], $row['topic_last_poster_colour']),
							'TOPIC_TYPE'				=> $topic_type,

							'S_TOPIC_GLOBAL'		=> (!$forum_id) ? true : false,
							'S_TOPIC_TYPE'			=> $row['topic_type'],
							'S_USER_POSTED'			=> (!empty($row['mark_type'])) ? true : false,
							'S_UNREAD_TOPIC'		=> $unread_topic,

							'S_TOPIC_REPORTED'		=> (!empty($row['topic_reported']) && $auth->acl_get('m_report', $forum_id)) ? true : false,
							'S_TOPIC_UNAPPROVED'	=> $topic_unapproved,
							'S_POSTS_UNAPPROVED'	=> $posts_unapproved,

							'U_LAST_POST'			=> $view_topic_url . '&amp;p=' . $row['topic_last_post_id'] . '#p' . $row['topic_last_post_id'],
							'U_LAST_POST_AUTHOR'	=> get_username_string('profile', $row['topic_last_poster_id'], $row['topic_last_poster_name'], $row['topic_last_poster_colour']),
							'U_TOPIC_AUTHOR'		=> get_username_string('profile', $row['topic_poster'], $row['topic_first_poster_name'], $row['topic_first_poster_colour']),
							'U_NEWEST_POST'			=> $view_topic_url . '&amp;view=unread#unread',
							'U_MCP_REPORT'			=> append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=reports&amp;mode=reports&amp;t=' . $result_topic_id, true, $user->session_id),
							'U_MCP_QUEUE'			=> $u_mcp_queue,
						);
					}
					else  // Search Posts
					{
					// We will ignore the friends or foe feature for RSS feeds, all posts will display. These lines are deliberately left in for comparison with future search.php releases.
					// 	if ((isset($zebra['foe']) && in_array($row['poster_id'], $zebra['foe'])) && (!$view || $view != 'show' || $post_id != $row['post_id']))
					// 	{
					// 		$template->assign_block_vars('searchresults', array(
					// 		'S_IGNORE_POST' => true,
					// 		'L_IGNORE_POST' => sprintf($user->lang['POST_BY_FOE'], $row['username'], "<a href=\"$u_search&amp;start=$start&amp;p=" . $row['post_id'] . '&amp;view=show#p' . $row['post_id'] . '">', '</a>'))
					// 		);
					// 		continue;
					// 	}

						// Replace naughty words such as farty pants
						$row['post_subject'] = censor_text($row['post_subject']);

						if ($row['display_text_only'])
						{
							// now find context for the searched words
							$row['post_text'] = get_context($row['post_text'], array_filter(explode('|', $hilit), 'strlen'), $return_chars);
							$row['post_text'] = bbcode_nl2br($row['post_text']);
						}
						else
						{
							// Second parse bbcode here
							if ($row['bbcode_bitfield'])
							{
								$bbcode->bbcode_second_pass($row['post_text'], $row['bbcode_uid'], $row['bbcode_bitfield']);
							}

							$row['post_text'] = bbcode_nl2br($row['post_text']);
							$row['post_text'] = smiley_text($row['post_text']);

							if (!empty($attachments[$row['post_id']]))
							{
								parse_attachments($forum_id, $row['post_text'], $attachments[$row['post_id']], $update_count);

								// we only display inline attachments
								unset($attachments[$row['post_id']]);
							}
						}

						if ($hilit)
						{
							// post highlighting
							$row['post_text'] = preg_replace('#(?!<.*)(?<!\w)(' . $hilit . ')(?!\w|[^<>]*(?:</s(?:cript|tyle))?>)#is', '<font size="3" color="red"><strong>$1</strong></font>', $row['post_text']); //%%RM replace stylesheet formatting with direct html for feed highlighting, see 'MESSAGE' line below for example
							$row['post_subject'] = preg_replace('#(?!<.*)(?<!\w)(' . $hilit . ')(?!\w|[^<>]*(?:</s(?:cript|tyle))?>)#is', '$1', $row['post_subject']); // %%RM work-around for post subject, text formatting for the highlight whacks the feed link/subject, results vary with the rss reader but all are defective.
						}

						$tpl_ary = array(
							'POST_AUTHOR_FULL'		=> get_username_string('full', $row['poster_id'], $row['username'], $row['user_colour'], $row['post_username']),
							'POST_AUTHOR_COLOUR'	=> get_username_string('colour', $row['poster_id'], $row['username'], $row['user_colour'], $row['post_username']),
							'POST_AUTHOR'			=> get_username_string('username', $row['poster_id'], $row['username'], $row['user_colour'], $row['post_username']),
							'U_POST_AUTHOR'			=> get_username_string('profile', $row['poster_id'], $row['username'], $row['user_colour'], $row['post_username']),

							'POST_SUBJECT'		=> $row['post_subject'],
							'PUB_DATE'			=> str_replace('UTC', 'UT', date("D, d M Y H:i T", $row['post_time'])),
							'POST_DATE'			=> $user->format_date($row['post_time']),
							'MESSAGE'			=> str_replace(array('./images', '<a href="#" onclick="selectCode(this); return false;">Select all</a>'), array($xml_root_path . 'images', '') , $row['post_text']) //fix for smiles and code "code"
						);
					}

					$template->assign_block_vars('searchresults', array_merge($tpl_ary, array(

						'RSS_TOPIC_AUTHOR'	=> ($authmailallow['user_allow_viewemail'] == 1 && $row['topic_last_poster_name'] != 'Anonymous') ? '<dc:creator>' . $row['topic_last_poster_name'] . '</dc:creator>' : '',
						'FORUM_ID'			=> $forum_id,
						'TOPIC_ID'			=> $result_topic_id,
						'POST_ID'			=> ($show_results == 'posts') ? $row['post_id'] : false,

						'FORUM_TITLE'		=> $row['forum_name'],
						'TOPIC_TITLE'		=> $topic_title,
						'TOPIC_REPLIES'		=> $replies,
						'TOPIC_VIEWS'		=> $row['topic_views'],

						'U_VIEW_TOPIC'		=> $view_topic_url,
						'U_VIEW_FORUM'		=> ("{$xml_root_path}viewforum.$phpEx" . '?f=' . $forum_id),
						'U_VIEW_POST'		=> (!empty($row['post_id'])) ? ("{$xml_root_path}viewtopic.$phpEx" . "?" . "f=$forum_id&amp;t=" . $row['topic_id'] . '&amp;p=' . $row['post_id'] . (($u_hilit) ? '&amp;hilit=' . $u_hilit : '')) . '#p' . $row['post_id'] : '')
					));
				}

				if ($topic_id && ($topic_id == $result_topic_id))
				{
					$template->assign_vars(array(
						'RSS_SEARCH'		=> true,
						'SEARCH_TOPIC'		=> $topic_title,
						'U_SEARCH_TOPIC'	=> $view_topic_url
					));
				}
			}
			unset($rowset);

			// Update rss_track table with search information
			if ($author || $author_id || $keywords)
			{
				if ($author || $author_id)
				{
					($author) ? $username = addslashes($author) : $username = addslashes(get_username_string('username', $author_id, 0, 0));
				}
				if ($keywords)
				{
					$keywords = str_replace(' ', '+', $keywords);
				}

				if ($username && $keywords)
				{
					$temp = $username . ' + ' . $keywords;
				}
				elseif ($username)
				{
					$temp = $username;
				}
				else
				{
					$temp = $keywords;
				}

				$temp = $user->lang['STATS_FEEDTYPE_SEARCH'] . $temp . $user->lang['PIPE'];

				$sql = 'UPDATE ' . RSS_TRACK . "
				SET rss_feed_type = '$temp'
				WHERE rss_id = 2";
				$db->sql_query($sql);
			}

			page_header(($l_search_title) ? $l_search_title : sprintf($user->lang['SEARCH']), false);
			header('Content-type: application/xml; charset=utf-8');

			$template->set_filenames(array(
				'body' => 'rss_feed_body.html')
			);

			page_footer();
		die();
		}

}
else
{
	{ // Start of RSS forum-feed code, let's get the forum number the reader is viewing -- %%RM

	include_once($phpbb_root_path . 'includes/bbcode.' . $phpEx); // %%RM

	// Below covers people who have not edited their admin files to add the config switch,
	// it will display if the $timing_on variable is set to 1 in the initial variables at page top.

	if ($config['rss_timing'])
	{
		$time_start = microtime(true); // timing code - start
	}

		if ($forum_id != 0)
		{
			$sql_from = FORUMS_TABLE . ' f';
			$lastread_select = '';

			// Grab appropriate forum data
			if ($config['load_db_lastread'] && $user->data['is_registered'])
			{
				$sql_from .= ' LEFT JOIN ' . FORUMS_TRACK_TABLE . ' ft ON (ft.user_id = ' . $user->data['user_id'] . '
					AND ft.forum_id = f.forum_id)';
				$lastread_select .= ', ft.mark_time';
			}

			if ($user->data['is_registered'])
			{
				$sql_from .= ' LEFT JOIN ' . FORUMS_WATCH_TABLE . ' fw ON (fw.forum_id = f.forum_id AND fw.user_id = ' . $user->data['user_id'] . ')';
				$lastread_select .= ', fw.notify_status';
			}

			$sql = "SELECT f.* $lastread_select
				FROM $sql_from
				WHERE f.forum_id = $forum_id";
			$result = $db->sql_query($sql);
			$forum_data = $db->sql_fetchrow($result);
			$db->sql_freeresult($result);

			if ((!$forum_data) && ($forum_id != 0))
			{
			trigger_error('NO_FORUM');
			}
		}
	}

 	$bbcode = new bbcode(base64_encode($bbcode_bitfield));

// Set up SQL query and limit and find out whether it's a forum feed or a topic feed to set up Atom link
// for validation and make sure it's a valid topic request

	if ($forum_id && $topic_id)
	{
			$sql = 'SELECT topic_title, forum_id
				FROM ' . TOPICS_TABLE . "
				WHERE topic_id = $topic_id";
			$result = $db->sql_query($sql);
			$row =  $db->sql_fetchrow($result);
			$topic_title = $row['topic_title'];
			$test = $row['forum_id'];
			$db->sql_freeresult($result);

			if (!$topic_title || $test != $forum_id)
			{
				trigger_error('NO_TOPIC');
			}

			$rss_prefix = $topic_title . $user->lang['SITENAME_PREFIX_TOPIC'];

		if (strlen($topic_title) > 44)
		{
			$trunc = request_var('trunc', strpos($topic_title, ' ', 45));
			$topic_title = substr($topic_title, 0, $trunc) . '&hellip;';
		}
		$topic_title = substr($user->lang['STATS_FEEDTYPE_TOPIC'], 0, 20) . $topic_title . $user->lang['PIPE'];

		$sql = 'UPDATE ' . RSS_TRACK . "
		SET rss_feed_type = '$topic_title'
		WHERE rss_id = 2";
		$db->sql_query($sql);

		if (!$auth->acl_get('f_list', $forum_id))
		{
			// if the user does not have permissions to list this forum, error
			trigger_error('LOGIN_RSS_SUBSCRIBE');
		}

		$rss_atom_suffix = '?f=' . $forum_id . '&t=' . $topic_id;
		$sql_where = "WHERE p.forum_id = $forum_id AND p.topic_id = $topic_id";
		$sql_limit = $config['rss_max_posts'];
	}
	elseif ($forum_id && !$topic_id)
	{
		if (!$auth->acl_get('f_list', $forum_id))
		{
			// if the user does not have permissions to list this forum, error
			trigger_error('LOGIN_RSS_SUBSCRIBE');
		}

		$sql = 'SELECT forum_name
				FROM ' . FORUMS_TABLE . "
				WHERE forum_id = $forum_id";
		$result = $db->sql_query($sql);

		$forumname = $db->sql_fetchfield('forum_name');
		$db->sql_freeresult($result);
		$rss_prefix = $forumname . $user->lang['SITENAME_PREFIX_FORUM'];

		if (strlen($forumname) > 39)
		{
			$trunc = request_var('trunc', strpos($forumname, ' ', 40));
			$forumname = substr($forumname, 0, $trunc) . '&hellip;';
		}
		$temp = substr($user->lang['STATS_FEEDTYPE_FORUM'], 0, 20) . $forumname . $user->lang['PIPE'];

		$sql = 'UPDATE ' . RSS_TRACK . "
			SET rss_feed_type = '$temp'
			WHERE rss_id = 2";
		$db->sql_query($sql);

		$rss_atom_suffix = ('?f=' . $forum_id);
		$sql_where = "WHERE p.forum_id = $forum_id";
		$sql_limit = $config['rss_max_posts'];
	}
	elseif ($cat != 0)
	{
		$sql = 'SELECT forum_name, forum_type
			FROM ' . FORUMS_TABLE . "
			WHERE forum_id = $cat";
		$result = $db->sql_query($sql);
		$row =  $db->sql_fetchrow($result);

		if ($row['forum_type'] != 0 || !$row)
		{
			trigger_error('NO_CATEGORY');
		}
		$rss_prefix = $row['forum_name'] . $user->lang['SITENAME_PREFIX_CAT'];

		$forumname = $row['forum_name'];
		if (strlen($forumname) > 39)
		{
			$trunc = request_var('trunc', strpos($forumname, ' ', 40));
			$forumname = substr($temp, 0, $trunc) . '&hellip;';
		}
		$temp = substr($user->lang['STATS_FEEDTYPE_CAT'], 0, 20) . $forumname . $user->lang['PIPE'];

		$db->sql_freeresult($result);

		$sql = 'UPDATE ' . RSS_TRACK . "
			SET rss_feed_type = '$temp'
			WHERE rss_id = 2";
		$db->sql_query($sql);

		if (!$auth->acl_get('f_list', $cat))
		{
			// if the user does not have permissions to list this category - error
			trigger_error('LOGIN_RSS_CATEGORY');
		}

		$rss_atom_suffix = ('?cat=' . $cat);
		$sql_where = "WHERE f.parent_id = $cat";
		$sql_limit = $config['rss_max_posts'];
	}
	elseif ($uid != 0) // Set up Atom link for user feed and error check for valid user id
	{
		$sql = "SELECT username
			FROM " . USERS_TABLE . "
			WHERE user_id = $uid
			AND user_type IN (" . USER_NORMAL . ', ' . USER_FOUNDER . ')';
		$result = $db->sql_query($sql);
		$row = $db->sql_fetchrow($result);

		if (!$row)
		{
			trigger_error('NO_USER');
		}
		$rss_prefix = $row['username'] . $user->lang['SITENAME_PREFIX_USR'];
		$temp = substr($user->lang['STATS_FEEDTYPE_USR'], 0, 20) . addslashes($row['username']) . $user->lang['PIPE'];
		$db->sql_freeresult($result);

		$sql = 'UPDATE ' . RSS_TRACK . "
			SET rss_feed_type = '$temp'
			WHERE rss_id = 2";
		$db->sql_query($sql);

		$rss_atom_suffix = ('?uid=' . $uid);
		$sql_where = "WHERE u.user_id = $uid";
		$sql_limit = $config['rss_max_posts'];
	}
	else // Default, main (board) feed (f=0)
	{
		if ($topic_id)
		{
			redirect($phpbb_root_path . 'rss.' . $phpEx . '?f=' . $forum_id , false, false);
		}
		//	$sql_where = "WHERE post_id LIKE '%'";
		$sql_where = ''; // this is just so we can use a single query for all 5 cases. This seems to be slightly faster than the previous line
		$sql_limit = $config['rss_max_posts_main'];
		$rss_prefix = $user->lang['SITENAME_PREFIX_MAIN'];

		$temp = substr($user->lang['STATS_FEEDTYPE_MAIN'], 0, 20) . $user->lang['PIPE'];
		$sql = 'UPDATE ' . RSS_TRACK . "
			SET rss_feed_type = '$temp'
			WHERE rss_id = 2";
		$db->sql_query($sql);

		$rss_atom_suffix = '?f=' . $forum_id;
	}

	// first array (static)
	$template->assign_vars(array(
		'RSS_SITENAME'		=> $rss_prefix . ' :: ' . htmlspecialchars($config['sitename']),
		'RSS_SEARCH'		=> false,
		'XML_SITE'			=> htmlspecialchars($config['server_protocol'] . $config['server_name'] . $forum_folder),
		'ATOM_LINK'			=> htmlspecialchars($config['server_protocol'] . $config['server_name'] . $_SERVER['PHP_SELF'] . $rss_atom_suffix),
		'MANAGING_EDITOR'	=> htmlspecialchars($config['rss_managing_editor_email'] . ' (' . $config['rss_managing_editor'] . ')'),
		'RSS_DESCRIPTION'	=> htmlspecialchars($config['site_desc']),
		'RSS_LANGUAGE'		=> str_replace('_', '-', $config['default_lang']),
		'RSS_TTL'			=> $config['rss_ttl']
		));

	// temporarily save the config values in memory so the feed loop doesn't go to disk to get them
	$gzip_compress = request_var('gzip_compress', $config['gzip_compress']);
	$rss_timing = request_var('rss_timing', $config['rss_timing']);
	$include_topic_views = request_var('include_topic_views', $config['rss_include_topic_views']);
	$rss_show_reply_count = request_var('rss_show_reply_count', $config['rss_show_reply_count']);
	$rss_founder_only = request_var('rss_founder_only', $config['rss_founder_only']);
	$test = true;

	$query = "
		SELECT p.topic_id, p.forum_id, p.post_time, p.post_id, p.post_subject, p.post_text, p.bbcode_bitfield, p.bbcode_uid, u.username, t.topic_title, f.left_id, f.parent_id, f.right_id as aantal_posts
		FROM " . POSTS_TABLE . " p JOIN " . USERS_TABLE . " u on p.poster_id = u.user_id JOIN " . TOPICS_TABLE . " t on p.topic_id = t.topic_id JOIN ". FORUMS_TABLE ." f on p.forum_id = f.forum_id
		$sql_where
		GROUP BY post_id
		ORDER BY p.post_time DESC
	";	$result = $db->sql_query_limit( $query, $sql_limit, 0 );

	// feed loop
	while( $row = $db->sql_fetchrow($result) )
	{
		$sql_view_post ="SELECT * FROM " . POSTS_TABLE . "
		WHERE post_time = ". $row['post_time'] . "";
		$res_views_post = $db->sql_query($sql_view_post);
		$row_views_post = $db->sql_fetchrow($res_views_post);
		if ($include_topic_views || $rss_show_reply_count)
		{
			$sql_view ="SELECT * FROM " . TOPICS_TABLE . "
			WHERE topic_id = ". $row['topic_id'] . "";
			$res_views = $db->sql_query($sql_view);
			$row_views = $db->sql_fetchrow($res_views);
		}
		$sql_session ="SELECT * FROM " . SESSIONS_TABLE . "
		WHERE session_user_id = ". $user->data['user_id'] . "";
		$forum_id = $row['forum_id'];

		if ($config['rss_total_stats'])
		{
			if (isset($user->data['session_page']) && !$user->data['is_bot'] && strpos($user->data['session_page'], '&t=' . $topic_id) === false)
			{
			$sql = 'UPDATE ' . POSTS_TABLE . '
				SET post_requests_rss = post_requests_rss + 1
				WHERE post_time = '. $row['post_time'] . "";
				$db->sql_query($sql);
			}
		}

	// Replies
	$replies = '';
	if ($include_topic_views)
	{
		$replies = '<em>' . $user->lang['TOPIC_VIEWS'] . '</em>&nbsp;&nbsp;' . $row_views['topic_views'];
	}
	if ($rss_show_reply_count)
	{
		$replies .= ($auth->acl_get('m_approve', $forum_id)) ? (($include_topic_views) ? '&nbsp;|&nbsp;' : '') . '<em>' . $user->lang['TOPIC_REPLIES'] . '</em>&nbsp;&nbsp;' . $row_views['topic_replies_real'] : (($include_topic_views) ? '&nbsp;|&nbsp;' : '') . '<em>' . $user->lang['TOPIC_REPLIES'] . '</em>&nbsp;&nbsp;' . $row_views['topic_replies'];
	}
	if ($config['rss_post_views'])
	{
		$replies .= (($include_topic_views || $rss_show_reply_count) ? '&nbsp;|&nbsp;' : '') . $user->lang['POST_VIEWS_RSS'] . $row_views_post['post_requests_rss'];
	}
	if  ($config['rss_total_stats'] && $test)
	{
		$test = false; // turn stats off after the first post, only the first gets the stats line
		if (!$rss_founder_only)
		{
			$replies .= '<br />' . $user->lang['TOTAL_VIEWS_RSS'] . $rss_total_views . ' ' . $user->lang['RSS_LAST_RESET'] . ' ' . $rss_count_start . ' | ' . $user->lang['LAST_RSS_REQUEST'] . $rss_last_request;
		}
		elseif ($rss_founder_only && (($user->data['user_type'] == USER_FOUNDER) || $auth->acl_getf_global('m_')))
		{
			$replies .= '<br />' . $user->lang['TOTAL_VIEWS_RSS'] . $rss_total_views . ' ' . $user->lang['RSS_LAST_RESET'] . ' ' . $rss_count_start . ' | ' . $user->lang['LAST_RSS_REQUEST'] . $rss_last_request;
		}
	}
	if ($replies)
	{
		$replies = '<br/><br/>' . '<font color="#9999CC">' . $replies . '</font>';
	}

	if ($auth->acl_get('f_read', $forum_id))
		{
			// Parse the message and subject
			$message = censor_text($row['post_text']);
			$forum_folder = (strlen($config['script_path']) > 1) ? $config['script_path'] . '/' : '/' ;

			// Second parse bbcode here
			if ($row['bbcode_bitfield'])
			{
				$bbcode->bbcode_second_pass($message, $row['bbcode_uid'], $row['bbcode_bitfield']);
			}
			$message = bbcode_nl2br($message);
			$message = smiley_text($message);
			$message = str_replace('./images', $xml_root_path . 'images' , $message); //fix for smiles
			$message = str_replace('<a href="#" onclick="selectCode(this); return false;">Select all</a>','',$message); // fix for code copy
			$message = str_replace(']]',']',$message); //fix for smiles
			$message = str_replace(array('<cite>', '</cite>'), array('<cite><u>', '</cite></u><br />'), $message); // reformat name of quoted poster
			$message = str_replace('<blockquote class="uncited">','<em><b><font color = "#666666">' . '&nbsp;' . sprintf($user->lang['RSS_QUOTE']) . '</font></b></em><blockquote>', $message); //fix for uncited quotes
			$fids = $row['forum_id'];
			$ids = $row["topic_id"];
			$p_post_id = $row_views_post['post_id']; // %%RM
			$names = censor_text($row['post_subject']);
			$url_link = $config['server_protocol'].$config['server_name'].$forum_folder.'viewtopic.php?';

//		if ($rss_timing) // uncomment this line for demo to non founders, then comment out the line below
		if ($rss_timing && ($user->data['user_type'] == USER_FOUNDER)) // comment this line out and uncomment the line above to demo timing to non founders
		{
			$time_end = microtime(true); // timing code
			$time = round($time_end - $time_start, 5);

			// from functions.php /includes/functions.php, part of Generate page footer
			$run_cron = true;
			global $starttime;
			$starttime == '';
			$start_time = (empty($starttime)) ? $current_time : $starttime;

			$mtime = explode(' ', microtime());
			$totaltime = $mtime[0] + $mtime[1] - $starttime;

			$debug_output = $user->lang['TIME'] . sprintf('%.3fs | ' . $db->sql_num_queries() . $user->lang['QUERIES_GZIP'] . (($gzip_compress) ? $user->lang['ON'] :
				$user->lang['OFF']) . (($user->load) ?  $user->lang['SERVER_LOAD'] . $user->load : ''), $totaltime) . '%';

			if (function_exists('memory_get_usage'))
			{
				if ($memory_usage = memory_get_usage())
				{
					global $base_memory_usage;
					$memory_usage -= $base_memory_usage;
					$memory_usage = get_formatted_filesize($memory_usage);
					$debug_output .= $user->lang['MEMORY_USAGE'] . $memory_usage;
					if ($user->data['user_type'] == USER_FOUNDER) // only display "Explain" link to founders, in future maybe apply to entire timing section
					{
						// following line may be needed for I.E. It doesn't do relative references very well, (comment out the line below)
						// $debug_output .= ' | <a href="' . $config['server_protocol'] . $config['server_name'] . $_SERVER['PHP_SELF'] . $rss_atom_suffix . '&explain=1">' . sprintf($user->lang['RSS_EXPLAIN']) . '</a>';
						$debug_output .= ' | <a href="' . $phpbb_root_path . 'rss.' . $phpEx . $rss_atom_suffix . '&explain=1">' . $user->lang['RSS_EXPLAIN'] . '</a>';
					}
				}
			$timing_result = '<br /><br /><font color="#993300"><strong>' . $user->lang['SCRIPT_EXECUTION_TIME'] . '&nbsp;</strong></font>' . $time . '&nbsp;' .
				$user->lang['SECONDS'] . ' :: <font color="#993300"><strong>' . $user->lang['OUTPUT_FROM_DEBUG'] . '&nbsp;</strong></font>' . $debug_output . '</em></font>';
			}
		}

		$description = '<em>' . $user->lang['IN_TOPIC'] . '&nbsp;&nbsp;</em><strong>' . $row['topic_title'] . ',&nbsp;&nbsp;' . $row['username']
		. '</strong>&nbsp;<em>' . $user->lang['POSTED'] . '</em>' . '<br /><br />' . $message . $replies . $timing_result;

			// block variable array
			$template->assign_block_vars('feed', array(
			'TITLE'				=> $names,
			'LINK'				=> $url_link.'f='.$fids.'&amp;t='.$ids.'&amp;p=' . $p_post_id . '#p' . $p_post_id,
			'DESCRIPTION'		=> $description,
			'DC_CREATOR'		=> $row['username'],
			'PUB_DATE'			=> str_replace('UTC', 'UT', date("D, d M Y H:i:s T", $row['post_time'])),
			'REG_GUID'			=> $url_link . 'f='.$fids . '&amp;t=' . $ids . '&amp;p=' . $p_post_id . '#p' . $p_post_id)
		);

		}
	}

	$db->sql_freeresult($result);

	header('Content-type: application/xml; charset=utf-8');
	$template->set_filenames(array(
	'body' => 'rss_feed_body.html')
	);

	page_footer();
}
die();
?>